import axios from 'axios'
import store from '@/store'
import { Message } from 'element-ui'
import { getToken } from '@/utils/token-manage'
import { baseUrl } from '@/config/request'

const service = axios.create({
    baseURL: baseUrl,
    timeout: 30 * 1000,
    headers: { 'Content-Type': 'application/json;charset=utf-8' }
})

// request interceptor
service.interceptors.request.use(
    config => {
        if (store.getters.token && config.url !== '/olda-play-auth/oauth/token') config.headers['Authorization'] = getToken()
        return config
    },
    error => {
        return Promise.reject(error)
    }
)

service.interceptors.response.use(
    response => {
        const data = response.data
        if (data.code === '200') {
            return data
        } else {
            Message({
                message: data.msg || '接口调用错误,请稍后重试！',
                type: 'error',
                duration: 2000
            })
        }
        return Promise.reject(new Error(data.msg || 'Error'))
    },
    error => {
        if (error.response.status === 401) {
            Message({
                message: '登录状态失效或过期,请重新登录!',
                type: 'error',
                duration: 2000
            })
            // setTimeout(() => {
            //     store.dispatch('user/resetToken', true)
            // }, 2000)
        } else {
            Message({
                message: error.response && error.response.data && error.response.data.msg ? error.response.data.msg : error.message,
                type: 'error',
                duration: 2000
            })
        }
        return Promise.reject(error)
    }
)

export default service
